import useDictStore from '@/store/modules/dict'
import { getDicts } from '@/api/system/dict/data'

/**
 * 获取字典数据
 */
export function useDict(...args) {
  const res = ref({});
  return (() => {
    args.forEach((dictType, index) => {
      res.value[dictType] = [];
      const dicts = useDictStore().getDict(dictType);
      if (dicts) {
        res.value[dictType] = dicts;
      } else {
        getDicts(dictType).then(resp => {
          res.value[dictType] = resp.map(p => ({
            label: p.label,
            // value: p.value,
            value: formatValue(p.value, p.dataType),
            elTagType: p.listClass,
            elTagClass: p.cssClass,
          }))
          useDictStore().setDict(dictType, res.value[dictType]);
        })
      }
    })
    return toRefs(res.value);
  })()
}

export function formatValue(dictData, valueType) {
  let value;
  switch (valueType) {
    case 0: // 字符串
      value = String(dictData);
      break;
    case 1: // 数值
      value = Number(dictData);
      break;
    case 2: // 布尔
      value = (dictData === 'true' || dictData === true);
      break;
    default:
      console.warn(`Unknown valueType: ${valueType}`);
  }
  return value;
}
